package com.atguigu.com.nio.nio_1_buffer;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.Set;

/**
 * @Author: robert.song
 * @Date: Created in 2021/8/8
 * Scattering：将数据写入到buffer时，可采用buffer数组，依次写入
 * Gathering：从buffer读取数据时，可用采用buffer数组，依次读取
 */
public class ScatteringAndGatheringTest {
    public static void main(String[] args) throws IOException {
        gathering();
        scattering();
    }

    public static void gathering() throws IOException {

        File file = new File(".\\gathering.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
        randomAccessFile.seek(0);
        FileChannel fileChannel = randomAccessFile.getChannel();
        System.out.println("FileChannel position " + fileChannel.position());
        ByteBuffer buffer = ByteBuffer.allocate(100);
        String str = "hello";
        buffer.clear();
        buffer.put(str.getBytes());
        buffer.flip();
        ByteBuffer buffer2 = ByteBuffer.allocate(100);
        String str2 = " world";
        buffer2.clear();
        buffer2.put(str2.getBytes());
        buffer2.flip();
        ByteBuffer[] bufferArray = {buffer, buffer2};
        fileChannel.write(bufferArray);
        randomAccessFile.close();
        fileChannel.close();
    }

    public static void scattering() throws IOException {

        RandomAccessFile randomAccessFile = new RandomAccessFile(
                "/Users/yangpeng/Documents/360/code/QiwooSample/NIOSample/src/com/nio/sample/file.txt", "rw");
        randomAccessFile.seek(0);
        FileChannel fileChannel = randomAccessFile.getChannel();
        ByteBuffer buffer = ByteBuffer.allocate(5);
        ByteBuffer buffer2 = ByteBuffer.allocate(100);
        ByteBuffer[] bufferArray = {buffer, buffer2};
        fileChannel.read(bufferArray);
        buffer.flip();
        while (buffer.hasRemaining()) {
            System.out.print((char) buffer.get());
        }
        System.out.println("");
        buffer2.flip();
        while (buffer2.hasRemaining()) {
            System.out.print((char) buffer2.get());
        }
        randomAccessFile.close();
        fileChannel.close();
    }
}
